<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/15
 * Time: 15:22
 */
namespace app\shop\controller;
use think\Db;
class Coupon extends Base
{
    /**
     * 任务管理数据
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function homePage(){
        extract(input());
        $search = input('param.search/a');
        $page = input('param.page');
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }

        $search = $this->search($search, $page);
        //搜索条件
        $map = [];
        //任务名称
        if($search[0] != ""){
            $map['coupon_name'] = ['like',"%" . $search[0] . "%"];
        }
        $map['coupon_status'] = ['<>',4];
        //任务类型
        if($search[1] != ""){
            $map['coupon_status'] = $search[1];
        }
        $map['coupon_s_id'] = session('shop_id');
        $data = Db::name('shop_coupon')
            ->where($map)
            ->order('coupon_time desc')
            ->paginate(25);
        //----------------------------
        $types = ['全部', '上架', '已到期', '下架'];
        //----------------------------
        return $this->fetch ('coupon/home_page',['data'=>$data,'pages'=>$pages,'search'=>$search,'types'=>$types]);
    }


    /**
     * 获取当前商户的审核状态
     * @return \think\response\Json
     */
    public function getShopSta()
    {
        $shop = Db::name('shops')
            ->where('s_id',session('shop_id'))
            ->field('s_status,s_money')
            ->find();
        $shopstatus = $shop['s_status'];
        if($shopstatus == 1){
            return json(['status'=>0,'msg'=>'认证审核中！']);
        }elseif ($shopstatus == 2){
            if($shop['s_money'] <= 0){
                return json(['status'=>0,'msg'=>'您平台币余额为0，请先充值！']);
            }
            return json(['status'=>200,'msg'=>'ok']);
        }elseif ($shopstatus == 3){
            return json(['status'=>0,'msg'=>'您的认证审核被拒绝，请检查后重新提交审核']);
        }else{
            return json(['status'=>0,'msg'=>'您还没有认证，请先去认证']);
        }
    }
    /**
     * 发布任务和提交
     * @return mixed|\think\response\Json
     */
    public function release(){
        extract(input());
        $shop = Db::name('shops')
            ->where('s_id',session('shop_id'))
            ->field(['s_id','s_money','s_status','s_name','s_thumb','s_image','s_jianjie','s_active_status','s_active_num'])
            ->find();

        if(request ()->isPost ()){
            if($shop['s_status'] != 2){
                return json(['status'=>100,'msg'=>'未认证实名认证，去认证']);
            }
            if((int)$task_num <= 0){
                return json(['status'=>100,'msg'=>'数量不能小于0']);
            }
            if((int)$task_price <= 0){
                return json(['status'=>100,'msg'=>'兑换金币不能小于0']);
            }
            if($coupon_money <= 0){
                return json(['status'=>0,'msg'=>'面额不能为0']);
            }
            if($coupon_money > $task_price){
                return json(['status'=>0,'msg'=>'面额不能大于兑换所需的云币']);
            }
            if((int)$coupon_use_day <= 0){
                return json(['status'=>100,'msg'=>'使用期限不能小于0']);
            }
            if($shop['s_money'] <= 0 || $money > $shop['s_money'] || $task_num*$task_price > $shop['s_money']){
                return json(['status'=>100,'msg'=>'金额不足，请充值']);
            }

            //***********************************************************************
            if(!$task_image){
                return json(['status'=>100,'msg'=>'请上传图片']);
            }
            //***********************************************************************
            $param = [
                'coupon_s_id'=>session('shop_id'),
                'coupon_num'=>$task_num,//数量
                'coupon_price'=>$task_price,//单个金额
                'coupon_money'=>$coupon_money,//面额
                'coupon_name'=>$task_name,//名称
                'coupon_image'=>$task_image,//图片
                'coupon_start'=>$task_starttime,//开始时间
                'coupon_end'=>$task_endtime,//结束时间
                'coupon_use_day'=>$coupon_use_day,//使用期限
                'coupon_time'=>date('Y-m-d H:i:s')
            ];
            //*************************************************************

            Db::startTrans ();
            try{
                Db::name('shop_coupon')->insertGetId($param);
                Db::name('shops')->where('s_id', session('shop_id'))->setDec('s_money', $money);
                //入商户明细和商户消息
                allInShopDetail($money, 1, session('shop_id'), '新增卡券：' . $task_name,8);
                allInNotice('扣款', '您新增的卡券：' . $task_name . '，成功扣款' . ($money / 10) . '元！', 3, session('shop_id'));
                Db::commit();
                return json(['status' => 200, 'msg' => '新增成功']);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'新增失败']);
            }
        }
        return $this->fetch('coupon/release_task');
    }

    /**
     * 任务编辑 （若任务总金额变化，多退少补）
     * @return mixed|\think\response\Json
     */
    public function editTask(){
        extract(input());
        if(request ()->isPost ()){
            Db::startTrans ();
            try{
                $today = date('Y-m-d H:i:s');
                $update = [
                    'coupon_name' => $task_name,
                    'coupon_image' => $task_image,
                    'coupon_time' => $today,
                    'coupon_status' => $task_share_type, //1上架  3下架
                ];
                $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
                if($can['coupon_status'] != 1){
                    return json(['status'=>0,'msg'=>'只有上架的卡券才可以编辑']);
                }
                if($can['coupon_status'] == 1 && $task_share_type == 3){
                    $back = ($can['coupon_num'] - $can['coupon_get_num']) * $can['coupon_price'];
                    if ($back > 0) {
                        Db::name('shops')
                            ->where('s_id', $can['coupon_s_id'])
                            ->setInc('s_money', $back);
                        //入商户明细和商户消息
                        allInShopDetail($back, 2, $can['coupon_s_id'], $can['coupon_name'] . '优惠券下架退还',8);
                        allInNotice('优惠券下架退还', $can['coupon_name'] . '优惠券下架退还，返还' . ($back / 10) . '元！', 3, $can['coupon_s_id']);
                    }
                }
                Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
                Db::commit();
                return json(['status' => 200, 'msg' => '编辑成功']);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'编辑失败']);
            }
        }
        $data = Db::name('shop_coupon')
            ->where('coupon_id',$coupon_id)
            ->find();
        return $this->fetch('coupon/edit_task',['data'=>$data]);
    }



    /**
     * 基本信息（详情）
     * @return mixed
     */
    public function baseMessage(){
        $data = Db::name('shop_coupon')
            ->where('coupon_id',input('coupon_id'))
            ->find();
        $where = array();
        $where['mc_coupon_id'] = input('coupon_id');
        //1、列表
        $field = 'c.*';
        $field .= ',u.user_username,u.user_phone,u2.user_username user_username2,u2.user_phone user_phone2';
        $data2 = Db::table('up_my_shop_coupon')->alias('c')
            ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
            ->where($where)
            ->order('mc_time DESC')
//            ->page($page,20)
            ->field($field)
            ->select();
        return $this->fetch ('coupon/base_message',['data'=>$data,'data2'=>$data2]);
    }




    /**
     * 下架任务
     * @return \think\response\Json
     */
    public function offLine(){
        extract(input());
        Db::startTrans ();
        try{
            $today = date('Y-m-d H:i:s');
            $update = [
                'coupon_time' => $today,
                'coupon_status' => 3, //1上架  3下架
            ];
            $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
            if($can['coupon_status'] != 1){
                return json(['status'=>0,'msg'=>'只有上架的卡券才可以下架']);
            }
            $back = ($can['coupon_num'] - $can['coupon_get_num']) * $can['coupon_price'];
            if ($back > 0) {
                Db::name('shops')
                    ->where('s_id', $can['coupon_s_id'])
                    ->setInc('s_money', $back);
                //入商户明细和商户消息
                allInShopDetail($back, 2, $can['coupon_s_id'], $can['coupon_name'] . '优惠券下架退还',8);
                allInNotice('优惠券下架退还', $can['coupon_name'] . '优惠券下架退还，返还' . ($back / 10) . '元！', 3, $can['coupon_s_id']);
            }
            Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
            Db::commit();
            return json(['status' => 200, 'msg' => '成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'失败']);
        }
    }


    /**
     * 删除任务（只要还有未完成的，不管你做了没有，都不能删除）（）
     * @return \think\response\Json
     */
    public function deleteTask(){
        extract(input());
        $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
        if($can['coupon_status'] == 1){
            return json(['status'=>0,'msg'=>'只有已到期或下架的卡券才可以删除']);
        }
        $update = [
            'coupon_status' => 4
        ];
        $res = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }

    }
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function excelCoupon(){
        extract(input());
        $where = [
            'coupon_status' => ['<>',4]
        ];
        if($name){
            $where['coupon_name'] = ['like',"%" . $name . "%"];
        }
        if($type){
            $where['coupon_status'] = $type;
        }
        $data = Db::table('up_shop_coupon')
            ->where($where)
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                if($v['coupon_status'] == 1){
                    $data[$k]['coupon_status'] = '上架';
                }
                if($v['coupon_status'] == 2){
                    $data[$k]['coupon_status'] = '已到期';
                }
                if($v['coupon_status'] == 3){
                    $data[$k]['coupon_status'] = '下架';
                }
            }
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
        $cellname = [
            ['coupon_name','名称',30,'LEFT'],
            ['coupon_num','数量',15,'LEFT'],
            ['coupon_price','兑换价格',20,'LEFT'],
            ['coupon_money','面额',15,'LEFT'],
            ['coupon_get_num','领取数量',15,'LEFT'],
            ['coupon_use_num','核销数量',15,'LEFT'],
            ['coupon_start','领取开始日期',15,'LEFT'],
            ['coupon_end','领取结束日期',15,'LEFT'],
            ['coupon_use_day','领取使用期限(天)',15,'LEFT'],
            ['coupon_time','发布时间',15,'LEFT'],
            ['coupon_status','状态',15,'LEFT'],
        ];
        $res = exportExcel('卡券数据','coupon',$cellname,$data);
        return json($res);
    }

}